package com.example.SpringBoot_demo.controller;

import cn.dustlight.captcha.annotations.CodeParam;
import cn.dustlight.captcha.annotations.CodeValue;

import com.example.SpringBoot_demo.bean.LoginUser;
import com.example.SpringBoot_demo.service.ILoginService;
import com.example.SpringBoot_demo.util.EmailCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

@RestController
public class EmailController {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String sendEmail;
    /**
     *获取html中的内容*/
    private String build(String message){
        Context context = new Context();
        context.setVariable( "message" , message);
        String result = templateEngine.process("send" , context);//send对应send.html
        System.out.println(result);
        return result;
    }
    private String build2(String message){
        Context context = new Context();
        context.setVariable( "message" , message);
        String result = templateEngine.process("send2" , context);//send2对应send2.html
        System.out.println(result);
        return result;
    }
    /**
     * 发送邮箱验证码
     * 存储邮箱，验证码
    * */
    @GetMapping("sendCodeToEmail")
    public void sendMail(@CodeValue String code, Model model, @CodeParam String email, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws MessagingException, IOException {

        System.out.println("邮箱："+email);
        if (email==null){
            response.sendRedirect("verifyErrorMessage");
        }
        LoginUser user= loginService.getUserByEmail(email);
        if (user==null){
            response.sendRedirect("verifyErrorMessage");
        }


        Map<String,Object> map = EmailCode.getImageCode();//获取验证码


        String simpleCaptcha = "simpleCaptcha";
//        Context context = new Context();
//        context.setVariable( "email" , email);
//        model.addAttribute("email",email);
        request.getSession().setAttribute("emailName",email);


        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());//存入验证码
        request.getSession().setAttribute("codeTime",new Date().getTime());/////将生成时间存入session
        Object cko = session.getAttribute("simpleCaptcha") ; //验证码对象
        code = cko.toString();//获取验证码
        System.out.println("验证码："+code);
        String name = build(code);
          //创建一个发送复杂消息对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setSubject("");
       //邮件内容, setText()第二个参数表示是否开启解析html
        helper.setText(name,true);
        helper.setSubject("图书管理系统");//标题
        helper.setFrom( sendEmail);
        helper.setTo(email);
        javaMailSender. send(mimeMessage);
        model.addAttribute("users",user);
        request.setAttribute("users",user);

       response.sendRedirect("updatePasswordByEmail");
       return;

    }
    /**
     * 发送邮箱验证码
     * 存储邮箱，验证码
     * */
    @GetMapping("sendCodeToLogin")
    public void sendMailLogin(@CodeValue String code, Model model, @CodeParam String email, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws MessagingException, IOException {

        System.out.println("邮箱："+email);
//        if (email==null){
//            response.sendRedirect("loginErrorMessage");
//        }
        LoginUser user=loginService.getUserByEmail(email);
        if (user==null){
          response.sendRedirect("loginErrorMessage");
       }


        Map<String,Object> map = EmailCode.getImageCode();//获取验证码


        String simpleCaptcha = "simpleCaptcha";
//        Context context = new Context();
//        context.setVariable( "email" , email);
//        model.addAttribute("email",email);
        request.getSession().setAttribute("emailName",email);


        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());//存入验证码
        request.getSession().setAttribute("codeTime",new Date().getTime());/////将生成时间存入session
        Object cko = session.getAttribute("simpleCaptcha") ; //验证码对象
        code = cko.toString();//获取验证码
        System.out.println("验证码："+code);
        String name = build2(code);
        //创建一个发送复杂消息对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setSubject("");
        //邮件内容, setText()第二个参数表示是否开启解析html
        helper.setText(name,true);
        helper.setSubject("图书管理系统");//标题
        helper.setFrom( sendEmail);
        helper.setTo(email);
        javaMailSender. send(mimeMessage);
        model.addAttribute("users",user);
        request.setAttribute("users",user);
        response.sendRedirect("loginByEmail");
        return;



    }


/*
    @RequestMapping(value = "/emailcode")
    public String imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream os = response.getOutputStream();
        Map<String,Object> map = EmailCode.getImageCode( os);
        String simpleCaptcha = "simpleCaptcha";
        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
        request.getSession().setAttribute("codeTime",new Date().getTime());
        return null;
    }*/

/*
    @GetMapping("checkcode")
    public String checkcode(@CodeValue String code, HttpServletRequest request, HttpSession session ,HttpServletResponse response) throws Exception {

        System.out.println( " 验证码 "+code);

        String checkCode = request.getParameter("checkCode");
        Object cko = session.getAttribute("simpleCaptcha") ; //验证码对象
        if(cko == null){
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }
        String captcha = cko.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime")+"");
        if(StringUtils.isEmpty(code) || captcha == null || !(code.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "验证码错误！";
        } else if ((now.getTime()-codeTime)/1000/60>5) {
            //验证码有效时长为5分钟
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }else {
            session.removeAttribute("simpleCaptcha");
            response.sendRedirect("updatePasswordByEmail");
            return "1";
        }
    }*/
}
